<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
      }
      canvas {
        box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
      }
      .clear {
        width: 600px;
        height: 50px;
        border-radius: 10px;
        background-color: #E4E7ED;
        margin-top: 10px;
        font-size: 24px;
        text-align: center;
        line-height: 50px;
        cursor: pointer;
      }
      .clear:hover {
        background-color: #C0C4CC;
      }
    </style>
  </head>
  <body>
    <canvas width="600" height="400" tabindex="0"> </canvas>
    <div class="clear">
      清除画布
    </div>

    <div class="clear"> 回复 </div>
    <script>
      const canvas = document.querySelector("canvas");
      const ctx = canvas.getContext("2d");
      const clear = document.querySelector(".clear")
      const reset = document.querySelectorAll('.clear')[1]

      var arr = []

      // 监听鼠标进入 canvas, 监听鼠标指针按下和抬起
      canvas.addEventListener('mouseenter', () => {
        // 监听鼠标指针按下
        canvas.addEventListener('mousedown', (e) => {
           // 开始绘制路径
           ctx.beginPath()
          // 设置绘制的起点为当前点击的位置
          ctx.moveTo(e.offsetX, e.offsetY)
          // 监听键盘移动事件
          canvas.addEventListener('mousemove', draw)   
        })
        canvas.addEventListener('mouseup', () => {
          // 移除鼠标移动事件
          canvas.removeEventListener('mousemove', draw)
        })
      })


      function draw(e, noPush) {
         
        // 绘制线
        ctx.lineTo(e.offsetX, e.offsetY)
        if (!noPush) {
         arr.push({ offsetX: e.offsetX, offsetY: e.offsetY })
        }
        // 描边路径
        ctx.stroke()
   
      }

      clear.addEventListener('click', () => {
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
      })
    
     reset.addEventListener('click', () =>{
           for (let i = 0; i < arr.length; i++) {
            draw(arr[i], true)
           }
     })
    </script>
  </body>
</html>
